"""
RagFlow 客户端 GUI 知识库列表功能模块
"""

from PySide6.QtWidgets import QMessageBox, QDialog, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem, QPushButton, QHeaderView
from PySide6.QtWidgets import QWidget as QWidgetContainer

from ragflow_client.gui.features.base_feature import BaseFeature


class DatasetsFeature(BaseFeature):
    """知识库列表功能类"""
    
    def __init__(self, parent=None):
        """初始化知识库列表功能"""
        super().__init__(parent)
    
    def execute(self):
        """执行知识库列表功能"""
        # 验证API配置
        if not self.validate_api_config(check_kb_id=False):
            return
        
        # 创建服务
        service = self.create_service()
        
        # 获取知识库列表
        try:
            status, result = service.list_datasets()
            if status:
                # 显示知识库列表
                datasets = result
                if not datasets:
                    QMessageBox.information(self.parent, "知识库列表", "没有找到知识库")
                    return
                
                # 创建内容部件
                content_widget = QWidget()
                layout = QVBoxLayout(content_widget)
                
                # 创建表格
                table = QTableWidget()
                table.setColumnCount(4)
                table.setHorizontalHeaderLabels(["ID", "名称", "描述", "操作"])
                table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                table.setRowCount(len(datasets))
                
                # 填充表格
                for i, dataset in enumerate(datasets):
                    table.setItem(i, 0, QTableWidgetItem(dataset.get("id", "")))
                    table.setItem(i, 1, QTableWidgetItem(dataset.get("name", "")))
                    table.setItem(i, 2, QTableWidgetItem(dataset.get("description", "")))
                    
                    # 创建操作按钮
                    select_button = QPushButton("选择")
                    dataset_id = dataset.get("id", "")
                    dataset_name = dataset.get("name", "")
                    select_button.clicked.connect(lambda checked, id=dataset_id, name=dataset_name: self.select_dataset(id, name))
                    
                    # 添加按钮到表格
                    button_container = QWidgetContainer()
                    button_layout = QHBoxLayout(button_container)
                    button_layout.addWidget(select_button)
                    button_layout.setContentsMargins(0, 0, 0, 0)
                    table.setCellWidget(i, 3, button_container)
                
                layout.addWidget(table)
                
                # 创建关闭按钮
                close_button = QPushButton("关闭")
                close_button.clicked.connect(lambda: self.window.close())
                layout.addWidget(close_button)
                
                # 创建窗口
                self.window = self.create_window("知识库列表", content_widget)
                self.window.show()
            else:
                QMessageBox.critical(self.parent, "错误", f"获取知识库列表失败: {result}")
        except Exception as e:
            QMessageBox.critical(self.parent, "错误", f"获取知识库列表失败: {str(e)}")
    
    def select_dataset(self, dataset_id: str, dataset_name: str) -> None:
        """
        选择知识库
        
        Args:
            dataset_id: 知识库 ID
            dataset_name: 知识库名称
        """
        # 更新界面
        if hasattr(self.parent, "kb_id_edit") and hasattr(self.parent, "kb_name_edit"):
            self.parent.kb_id_edit.setText(dataset_id)
            self.parent.kb_name_edit.setText(dataset_name)
            
            # 关闭窗口
            if self.window:
                self.window.close()
            
            # 提示用户
            QMessageBox.information(self.parent, "成功", f"已选择知识库: {dataset_name}")
        else:
            QMessageBox.critical(self.parent, "错误", "无法更新知识库信息")